package com.lianxi.nmms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.nmms.constant.DictConstant;
import com.lianxi.nmms.constant.ProductConstant;
import com.lianxi.nmms.dao.ProductMapper;
import com.lianxi.nmms.dao.ProductTypeMapper;
import com.lianxi.nmms.dao.SequenceMapper;
import com.lianxi.nmms.entity.*;
import com.lianxi.nmms.exception.*;
import com.lianxi.nmms.service.ProductService;
import com.lianxi.nmms.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 翔哥
 * 2025年09月29日
 */

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private ProductTypeMapper productTypeMapper;

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<Product> findPage(String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.PRODUCT_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.PRODUCT_DEFAULT_PAGE_SIZE;
        }

        PageHelper.startPage(Integer.valueOf(pageNo), Integer.valueOf(pageSize));
        List<Product> products = productMapper.selectAll();
        PageInfo<Product> proPage = new PageInfo<>(products);

        if (!"1".equals(pageNo) && proPage.getList().isEmpty()) {
            Integer page = Integer.parseInt(pageNo) - 1;
            proPage = findPage(page + "", pageSize);
        }
        return proPage;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<Product> findAll() {
        ProductExample productExample =new ProductExample();
        return productMapper.selectByExample(productExample);
    }

    @Override
    public void addProduct(String name, String price, String description, CommonsMultipartFile file, String typeId, HttpSession session) throws RequestParameterErrorException, ProductTypeExistException, FileUploadErrorException, ProductExistException {

        System.out.println(name + "       " + price + "       " + file + "       " + description + "       " + typeId);
        if (ParameterUtil.isNull(name) || ParameterUtil.isNull(price) || ParameterUtil.isNull(description) || file.isEmpty() || ParameterUtil.isNull(typeId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }
        ProductExample productExample = new ProductExample();
        productExample.or()
                .andNameEqualTo(name)
                .andProductTypeIdEqualTo(Integer.valueOf(typeId));
        List<Product> products = productMapper.selectByExample(productExample);
        if (!products.isEmpty()) {
            throw new ProductExistException("该商品已经存在了");
        }
        Product product = new Product();
        product.setName(name);
        product.setPrice(Double.valueOf(price));
        product.setDescription(description);
        product.setProductTypeId(Integer.valueOf(typeId));


        //获取no
        String NoName = ProductConstant.PRODUCT_FORMER;
        SequenceExample sequenceExample = new SequenceExample();
        sequenceExample.or()
                .andNameEqualTo(NoName);
        List<Sequence> sequences = sequenceMapper.selectByExample(sequenceExample);

        String no;
        if (sequences != null && !sequences.isEmpty()) {
            no = NoName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ParameterUtil.getSequence(sequences.get(0).getValue());
            sequences.get(0).setValue(ParameterUtil.getSequence(sequences.get(0).getValue()));
            sequenceMapper.updateByPrimaryKeySelective(sequences.get(0));

        } else {
            Sequence sequence = new Sequence();
            sequence.setName(NoName);
            sequence.setValue(ProductConstant.PRODUCT_NO_MIN);
            sequenceMapper.insertSelective(sequence);
            no = NoName + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ProductConstant.PRODUCT_NO_MIN;

        }
        product.setNo(no);


        //保存图片，返回地址值
        String path = ProductConstant.PRODUCT_IMAGE_ROOT + new SimpleDateFormat("yyyyMMdd").format(new Date());

        String url = session.getServletContext().getRealPath(path);
        File f = new File(url);
        f.mkdirs();
        product.setImage(path + File.separator + file.getOriginalFilename());


        try {
            productMapper.insertSelective(product);
            file.transferTo(new File(url, file.getOriginalFilename()));
        } catch (IOException e) {
            throw new FileUploadErrorException("上传商品的图片出错");
        }
    }


    @Override
    public Product findProductById(String id) throws RequestParameterErrorException {
        if(ParameterUtil.isNull(id)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        Product product = productMapper.selectByPrimaryKey(Integer.valueOf(id));
        return product;
    }

    @Override
    public void updateProduct(String id,String name, String price, String description, CommonsMultipartFile file, String typeId, HttpSession session) throws RequestParameterErrorException, ProductTypeExistException, ProductExistException, FileUploadErrorException {
        if (ParameterUtil.isNull(name) || ParameterUtil.isNull(price)|| ParameterUtil.isNull(description)  || ParameterUtil.isNull(typeId)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        ProductExample example = new ProductExample();
        example.or()
                .andNameEqualTo(name)
                .andProductTypeIdEqualTo(Integer.parseInt(typeId))
                .andIdNotEqualTo(Integer.parseInt(id));
        List<Product> products = productMapper.selectByExample(example);
        if (!products.isEmpty()) {
            throw new ProductExistException("该类型的商品已经存在");
        }

        Product product =new Product();
        product.setId(Integer.valueOf(id));
        product.setName(name);
        product.setPrice(Double.valueOf(price));
        product.setDescription(description);
        product.setProductTypeId(Integer.valueOf(typeId));
        if(file.isEmpty()){
            productMapper.updateByPrimaryKeySelective(product);
        }else {
            // 如果图片不为空,则表示需要修改图片
            // 修改商品图片时,需要先删除原来的商品图片
            // 获取原有的商品图片地址
            Product p = productMapper.selectByPrimaryKey(Integer.parseInt(id));
            String cp = session.getServletContext().getRealPath(p.getImage());
            File f = new File(cp);

            f.delete();
            String path = ProductConstant.PRODUCT_IMAGE_ROOT + new SimpleDateFormat("yyyyMMdd").format(new Date());
            // 获取基于服务器根目录的绝对路径
            cp = session.getServletContext().getRealPath(path);
            // 创建目录
            File f2 = new File(cp);
            f2.mkdirs();

            product.setImage(path + File.separator + file.getOriginalFilename());

            try {
                // 修改商品信息
                productMapper.updateByPrimaryKeySelective(product);

                // 上传商品图片
                file.transferTo(new File(cp, file.getOriginalFilename()));
            } catch (IOException e) {
                throw new FileUploadErrorException("上传商品图片失败");
            }

        }
    }

    @Override
    public void deleteProduct(String id,HttpSession session) throws ProductExistException, FileDeletionErrorException, ProductDeletionErrorException {

        Product product = productMapper.selectByPrimaryKey(Integer.valueOf(id));

        if (product == null) {
            throw new ProductExistException("商品不存在");
        }


        String imagePath = product.getImage();

        if (imagePath != null && !imagePath.isEmpty()) {

            String realPath = session.getServletContext().getRealPath(imagePath);
            File imageFile = new File(realPath);

            if (imageFile.exists()) {
                if (!imageFile.delete()) {
                    throw new FileDeletionErrorException("删除图片文件失败");
                }
            }
        }
        productMapper.deleteByPrimaryKey(Integer.valueOf(id));


    }


}
